package airplane.com.example.service;

import airplane.com.example.entry.Airplane;
import airplane.com.example.entry.Ticket;
import airplane.com.example.mapper.AirplaneMapper;
import airplane.com.example.mapper.TicketMapper;
import airplane.com.example.utilities.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class TickerServiceImpl implements TickerService {

    @Autowired
    TicketMapper ticketMapper;

    @Autowired
    AirplaneMapper airplaneMapper;

    @Override
    public Result insertTicket(Ticket ticket) {
        try {
            Airplane airplane = airplaneMapper.queryAirplaneByName(ticket.getAirplane());
            if (airplane == null) return new Result("不存在该班次!", false);
            if (airplane.getTicket() <= 0) return new Result("该班次无余票!", false);

            if (ticketMapper.insertTicket(ticket) != 0) {
                airplane.setTicket(airplane.getTicket() - 1);
                airplaneMapper.updateAirplane(airplane);
                return new Result("购票成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result("系统错误：购票失败!",false);
    }

    @Override
    public Result deleteTicketByAirplane(Ticket ticket) {
        try {
            if (ticketMapper.deleteTicketByAirplane(ticket) == 0) {
                return new Result("不存在该购票记录!",false);
            } else {
                Airplane airplane = airplaneMapper.queryAirplaneByName(ticket.getAirplane());
                if (airplane != null){
                    airplane.setTicket(airplane.getTicket() + 1);
                    airplaneMapper.updateAirplane(airplane);
                }
                return new Result("退票成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result("系统错误：退票失败!", false);
        }
    }

    // 分页查询
    @Override
    public List<Ticket> findByPage(Integer currentPage, Integer pageSize, String userName) {
        currentPage = (currentPage - 1) * pageSize;
        return ticketMapper.findByPage(currentPage, pageSize, userName);
    }

    // 查询总页数
    @Override
    public int findTotal() {
        return ticketMapper.findTotal();
    }
}
